//
//  MineOrderViewController.m
//  renmingongshe
//
//  Created by macbook on 2017/10/26.
//  Copyright © 2017年 xiaodian. All rights reserved.
//

#import "MineOrderViewController.h"
#import "LOGoodsTableViewCell.h"
#import "LOGoodsListModel.h"
#import "MineOrderDetailViewController.h"
#import "MineRefundViewController.h"
#import "LDPushOrderViewController.h"
#import "MineAssessViewController.h"
#import "RefundingViewController.h"
#import "RefundSuccessViewController.h"

@interface MineOrderViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UITableView *_tab;
    NSDictionary *_paraDic;
    NSInteger _selectType;
    NSInteger _LDselectType;
    NSString *_url;
    NSInteger _pageNumber;
    NSArray *_LOurlArr;
    NSMutableArray *_listArr;
    NSString *_type;
    NSString *_goodsId;
    NSString *_goodsImg;
}
@property (weak, nonatomic) IBOutlet UIButton *LOBtn;
@property (weak, nonatomic) IBOutlet UIButton *LDBtn;
@property (strong, nonatomic) UIView *footerView;
@property (weak, nonatomic) IBOutlet UIView *lineView;
@property (weak, nonatomic) IBOutlet UIView *LOView;
@property (weak, nonatomic) IBOutlet UIView *LDView;
@property (weak, nonatomic) IBOutlet UIView *LDLineView;
@end

@implementation MineOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.titleLabel.text = @"我的订单";
    _type = @"shop";
    _selectType = 0;
    _LDselectType = 0;
    _pageNumber = 1;
    _listArr = [NSMutableArray array];
    _url = API(MineAllOrder);
    _LOurlArr = @[API(MineAllOrder),API(MinePayOrder),API(MineSendOrder),API(MineReciveOrder),API(MineAssessOrder),API(MineRefundOrder)];
    _LDView.hidden = YES;
    _paraDic = @{@"type":_type, @"userToken":[Utils getUserToken], @"page":[NSNumber numberWithInteger:_pageNumber], @"pageSize":@"10"};
    [self downloadData:_url];
    [self createFooterView];
    [self createTableView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(OrderRefresh) name:@"OrderRefresh" object:nil];
}

- (void)OrderRefresh
{
    [_listArr removeAllObjects];
    [self downloadData:_url];
}

- (void)createFooterView
{
    _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 1)];
    _footerView.backgroundColor = RGB(232, 234, 234);
}

- (void)createTableView
{
    _tab = [[UITableView alloc] initWithFrame:CGRectMake(0, 158, WIDTH, HEIGHT-158) style:(UITableViewStyleGrouped)];
    _tab.delegate = self;
    _tab.dataSource = self;
    _tab.showsVerticalScrollIndicator = NO;
    [_tab setTableFooterView:_footerView];
    [_tab registerNib:[UINib nibWithNibName:@"LOGoodsTableViewCell" bundle:nil] forCellReuseIdentifier:@"LOGoodsTableViewCell"];
    [self.view addSubview:_tab];
    
    _tab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _pageNumber = 1;
        [_listArr removeAllObjects];
        _paraDic = @{@"type":_type, @"userToken":[Utils getUserToken], @"page":[NSNumber numberWithInteger:_pageNumber], @"pageSize":@"10"};
        [self downloadData:_url];

    }];
    _tab.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _pageNumber ++;
        _paraDic = @{@"type":_type, @"userToken":[Utils getUserToken], @"page":[NSNumber numberWithInteger:_pageNumber], @"pageSize":@"10"};
        [self downloadData:_url];
    }];
}

- (void)downloadData:(NSString *)url
{
    [self.view loadingOnAnyView];
    [THWManager PostHttp:url Parameters:_paraDic Success:^(id responseObject) {
        [self.view removeAnyView];
        
        if ([String(responseObject[@"status_code"]) isEqualToString:@"1008"]) {
            [self.view Message:responseObject[@"msg"]];
        }else{
            NSDictionary *dataDic = responseObject[@"data"];
            
            if ([dataDic[@"Rows"] count] != 0) {
                [_listArr addObjectsFromArray:dataDic[@"Rows"]];
            }else{
                [self.view Message:@"无更多数据"];
            }
            
            [_tab reloadData];
            [_tab.mj_header endRefreshing];
            [_tab.mj_footer endRefreshing];
        }
        
    } andFalse:^(NSError *error) {
        [self.view removeAnyView];
        [_tab.mj_header endRefreshing];
        [_tab.mj_footer endRefreshing];
    }];
}

- (IBAction)LineOnclick:(UIButton *)sender {
    _pageNumber = 1;
    _LOView.hidden = NO;
    _LDView.hidden = YES;
    _type = @"shop";
    _lineView.centerX = WIDTH/12;
    [_listArr removeAllObjects];
    _paraDic = @{@"type":_type, @"userToken":[Utils getUserToken], @"page":[NSNumber numberWithInteger:_pageNumber], @"pageSize":@"10"};
    [self downloadData:API(MineAllOrder)];
    [sender setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_LDBtn setTitleColor:[UIColor colorWithHex:0x999999] forState:UIControlStateNormal];
}
- (IBAction)LineDownClick:(UIButton *)sender {
    _pageNumber = 1;
    _LOView.hidden = YES;
    _LDView.hidden = NO;
    _type = @"line";
    _LDLineView.centerX = WIDTH/6;
    [_listArr removeAllObjects];
    _paraDic = @{@"type":_type, @"userToken":[Utils getUserToken], @"page":[NSNumber numberWithInteger:_pageNumber], @"pageSize":@"10"};
    [self downloadData:API(MineAllOrder)];
    [sender setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_LOBtn setTitleColor:[UIColor colorWithHex:0x999999] forState:UIControlStateNormal];
}

- (IBAction)selectClick:(UIButton *)sender {
    _pageNumber = 1;
    _paraDic = @{@"type":_type, @"userToken":[Utils getUserToken], @"page":[NSNumber numberWithInteger:_pageNumber], @"pageSize":@"10"};
    [_listArr removeAllObjects];
    _selectType = sender.tag-100;
    
    [UIView animateWithDuration:0.2 animations:^{
        _lineView.centerX = _selectType*WIDTH/6+WIDTH/12;
    }];
    _url = _LOurlArr[sender.tag-100];
    [self downloadData:_url];
}
- (IBAction)LDSelect:(UIButton *)sender {
    _pageNumber = 1;
    _paraDic = @{@"type":_type, @"userToken":[Utils getUserToken], @"page":[NSNumber numberWithInteger:_pageNumber], @"pageSize":@"10"};
    if (sender.tag == 204) {
        _LDselectType = sender.tag-202;
    }else{
        _LDselectType = sender.tag-200;
    }
    
    [_listArr removeAllObjects];
    
    [UIView animateWithDuration:0.2 animations:^{
        _LDLineView.centerX = _LDselectType*WIDTH/3+WIDTH/6;
    }];
    _url = _LOurlArr[sender.tag-200];
    [self downloadData:_url];
}

#pragma mark - UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = _listArr;
    return [arr[section][@"list"] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LOGoodsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LOGoodsTableViewCell"];
    if (_listArr.count != 0) {
        NSArray *arr = _listArr;
        GoodsListModel *model = [[GoodsListModel alloc]initWithDictionary:arr[indexPath.section][@"list"][indexPath.row] error:nil];
        [cell cellConfigureModel:model];
        cell.SaleLabel.hidden = YES;
    }
    
    cell.AssessClick = ^{
        _goodsId = _listArr[indexPath.section][@"list"][indexPath.row][@"goodsId"];
        _goodsImg = _listArr[indexPath.section][@"list"][indexPath.row][@"goodsImg"];
    };
    
    UIButton *btn = cell.toAcess;
    btn.frame =CGRectMake(WIDTH-70, 45, 60, 24);
    [btn setTitle:@"立即评价" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    
    btn.layer.borderWidth = 1;
    btn.tag = indexPath.section;
    btn.layer.borderColor = [UIColor redColor].CGColor;
    btn.layer.cornerRadius = 5;
    [btn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    if ([_listArr[indexPath.section][@"orderStatus"] integerValue] == 2) {
        if ([_listArr[indexPath.section][@"list"][indexPath.row][@"isGoodsAppraise"] boolValue]) {
            btn.hidden = YES;
        }else{
            btn.hidden = NO;
        }
    }else{
        btn.hidden = YES;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _listArr.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSDictionary *dic = _listArr[section];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 48)];
    view.backgroundColor = [UIColor whiteColor];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 8)];
    line.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
    [view addSubview:line];
    
    UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(10, line.bottom, 130, 40)];
    name.text = dic[@"shopName"];
    name.font = [UIFont systemFontOfSize:15];
    [view addSubview:name];
    
    UILabel *time = [[UILabel alloc]initWithFrame:CGRectMake(name.right, name.top, 130, 40)];
    time.text = dic[@"createTime"];
    time.font = [UIFont systemFontOfSize:12];
    time.textColor = [UIColor lightGrayColor];
    [view addSubview:time];
    
    UILabel *status = [[UILabel alloc]initWithFrame:CGRectMake(view.width-100, name.top, 90, 40)];
    status.font = [UIFont systemFontOfSize:14];
    status.text = dic[@"status"];
    status.textAlignment = NSTextAlignmentRight;
    status.textColor = [UIColor grayColor];
    [view addSubview:status];
    
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    NSDictionary *dic = _listArr[section];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
    view.backgroundColor= [UIColor whiteColor];
    
    UILabel *needPay = [[UILabel alloc]initWithFrame:CGRectMake(10, 12, 150, 40)];
    needPay.text = [NSString stringWithFormat:@"付款:￥%@",dic[@"needPay"]];
    needPay.font = [UIFont systemFontOfSize:14];
    needPay.textColor = [UIColor grayColor];
    NSDictionary *attrs = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:14]};
    CGSize Size_str=[needPay.text sizeWithAttributes:attrs];
    needPay.size = Size_str;
    [view addSubview:needPay];
    
    if ([_type isEqualToString:@"shop"]) {
        UILabel *ferightLabel = [[UILabel alloc] initWithFrame:CGRectMake(needPay.right, 0, 100, 40)];
        NSString *string;
        if ([dic[@"deliverMoney"]integerValue]>0) {
            string = [NSString stringWithFormat:@"(运费:%@元)", dic[@"deliverMoney"]];
        }else{
            string = @"(包邮)";
        }
        ferightLabel.text = string;
        ferightLabel.font = [UIFont systemFontOfSize:12];
        ferightLabel.textColor = [UIColor grayColor];
        [view addSubview:ferightLabel];
    }
    
    if ([_type isEqualToString:@"shop"]) {
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH-70, 8, 60, 24)];
        NSString *str;
        if([dic[@"orderStatus"] integerValue] == -3){
            str = @"修改退货";
        }else if ([dic[@"orderStatus"] integerValue] == -2) {
            str = @"立即付款";//待付款
        }else if ([dic[@"orderStatus"] integerValue] == 0) {
            str = @"立即退货";//待发货
        }else if ([dic[@"orderStatus"] integerValue] == 1) {
            str = @"确认收货";//待收货
        }else if ([dic[@"orderStatus"] integerValue] == 2) {
            str = @"立即退货";//待评价
        }else if ([dic[@"orderStatus"] integerValue] == -1) {
            btn.hidden = YES;//已取消
        }else{
            btn.hidden = YES;//退换货
        }
        [btn setTitle:str forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        [view addSubview:btn];
        btn.layer.borderWidth = 1;
        btn.layer.borderColor = [UIColor redColor].CGColor;
        btn.layer.cornerRadius = 5;
        btn.tag = section;
        [btn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(btn.left-70, 8, 60, 24)];
        NSString *str1;
        if ([dic[@"orderStatus"] integerValue] == -2) {
            btn1.hidden = YES;//待付款
        }else if ([dic[@"orderStatus"] integerValue] == 0) {
            btn1.hidden = YES;//待发货
        }else if ([dic[@"orderStatus"] integerValue] == 1) {
            str1 = @"立即退货";//待收货
        }else if ([dic[@"orderStatus"] integerValue] == 2) {
            btn1.hidden = YES;//待评价
        }else if ([dic[@"orderStatus"] integerValue] == -1) {
            btn1.hidden = YES;//已取消
        }else{
            btn1.hidden = YES;//退换货
        }
        [btn1 setTitle:str1 forState:UIControlStateNormal];
        [btn1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        btn1.titleLabel.font = [UIFont systemFontOfSize:14];
        [btn1 addTarget:self action:@selector(Btn1Click:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:btn1];
        btn1.tag = section;
        btn1.layer.borderWidth = 1;
        btn1.layer.borderColor = [UIColor redColor].CGColor;
        btn1.layer.cornerRadius = 5;
    }else{
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH-70, 8, 60, 24)];
        NSString *str;
        if ([dic[@"orderStatus"] integerValue] == -2) {
            str = @"立即付款";//待付款
        }else if ([dic[@"orderStatus"] integerValue] == 2) {
            str = @"立即评价";//待评价
        }else if ([dic[@"orderStatus"] integerValue] == -1) {
            btn.hidden = YES;//已取消
        }else{
            btn.hidden = YES;//退换货
        }
        [btn setTitle:str forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        [view addSubview:btn];
        btn.tag = section;
        btn.layer.borderWidth = 1;
        btn.layer.borderColor = [UIColor redColor].CGColor;
        btn.layer.cornerRadius = 5;
        [btn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(btn.left-70, 8, 60, 24)];
        NSString *str1;
        if ([dic[@"orderStatus"] integerValue] == -2) {
            //待付款
            btn1.hidden = YES;
        }else if ([dic[@"orderStatus"] integerValue] == 2) {
            btn1.hidden = YES;;//待评价
        }else if ([dic[@"orderStatus"] integerValue] == -1) {
            //已取消
            btn1.hidden = YES;
        }else{
            //退换货
            btn1.hidden = YES;
        }
        [btn1 setTitle:str1 forState:UIControlStateNormal];
        [btn1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        btn1.titleLabel.font = [UIFont systemFontOfSize:14];
        [btn1 addTarget:self action:@selector(Btn1Click:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:btn1];
        btn1.tag = section;
        btn1.layer.borderWidth = 1;
        btn1.layer.borderColor = [UIColor redColor].CGColor;
        btn1.layer.cornerRadius = 5;
    }
    return view;
}
- (void)editRefund:(NSInteger)tag
{
    [THWManager PostHttp:API(MineOrderRefund) Parameters:@{@"orderId":_listArr[tag][@"orderId"], @"userToken":[Utils getUserToken]} Success:^(id responseObject) {
        
        NSDictionary *_data = responseObject[@"data"][@"refunds"];
        
        if ([_data[@"refundStatus"]integerValue]==-1 ) {
            //退款失败
            RefundSuccessViewController *success = [[RefundSuccessViewController alloc]init];
            success.data = responseObject[@"data"][@"refunds"];
            success.isSuc = NO;;
            [self.navigationController pushViewController:success animated:YES];
        }else if([_data[@"refundStatus"]integerValue]==0){
            //等待处理
            RefundingViewController *refund = [[RefundingViewController alloc]init];
            
            refund.data = responseObject[@"data"][@"refunds"];
            refund.reasonDic = responseObject[@"data"][@"datas"];
            [self.navigationController pushViewController:refund animated:YES];
        }else if ([_data[@"refundStatus"]integerValue]==1)
        {
            //等待退款
            RefundingViewController *refund = [[RefundingViewController alloc]init];
            
            refund.data = responseObject[@"data"][@"refunds"];
            refund.reasonDic = responseObject[@"data"][@"datas"];
            [self.navigationController pushViewController:refund animated:YES];
        }else{
            //退款成功
            RefundSuccessViewController *success = [[RefundSuccessViewController alloc]init];
            success.data = responseObject[@"data"][@"refunds"];
            success.isSuc = YES;
            [self.navigationController pushViewController:success animated:YES];
        }
        
    } andFalse:^(NSError *error) {
        
    }];
}
- (void)BtnClick:(UIButton *)btn
{
    //按钮
    if ([btn.titleLabel.text isEqualToString:@"修改退货"]){
        
        [self editRefund:btn.tag];
    }else if ([btn.titleLabel.text isEqualToString:@"立即付款"]) {
        LDPushOrderViewController *pay = [[LDPushOrderViewController alloc] init];
        if ([_listArr[btn.tag][@"orderTypes"]integerValue]) {
            //线下
            pay.isLineOnOrder = NO;
        }else{
            //线上
            pay.isLineOnOrder = YES;
        }
        pay.lineId = _listArr[btn.tag][@"lineId"];
        pay.money = _listArr[btn.tag][@"needPay"];
        pay.orderNo = _listArr[btn.tag][@"orderNo"];
        pay.type = @"order";
        [self.navigationController pushViewController:pay animated:YES];
    }else if ([btn.titleLabel.text isEqualToString:@"立即评价"]){
        MineAssessViewController *assess = [[MineAssessViewController alloc]init];
        assess.goodsId = _goodsId;
        assess.goodsImg = _goodsImg;
        assess.type = _type;
        assess.orderId = _listArr[btn.tag][@"orderId"];
        [self.navigationController pushViewController:assess animated:YES];
    }else if ([btn.titleLabel.text isEqualToString:@"立即退货"]){
        [THWManager PostHttp:API(MineOrderRefund) Parameters:@{@"orderId":_listArr[btn.tag][@"orderId"], @"userToken":[Utils getUserToken]} Success:^(id responseObject) {
            
                MineRefundViewController *refund = [[MineRefundViewController alloc] init];
                refund.reasonDic = responseObject[@"data"][@"datas"];
                refund.moneyStr = responseObject[@"data"][@"totalMoney"];
                refund.orderId = responseObject[@"data"][@"orderId"];
                [self.navigationController pushViewController:refund animated:YES];
            
        } andFalse:^(NSError *error) {
            
        }];
    }else if ([btn.titleLabel.text isEqualToString:@"确认收货"]){
        [self.view loadingOnAnyView];
        [THWManager PostHttp:API(MineReceive) Parameters:@{@"orderId":_listArr[btn.tag][@"orderId"], @"userToken":[Utils getUserToken], @"type":@"shop"} Success:^(id responseObject) {
            [self.view removeAnyView];
            if ([String(responseObject[@"status"]) isEqualToString:@"-1"]) {
                [self.view Message:responseObject[@"msg"]];
            }else{
                [self.view Message:responseObject[@"msg"]];
                [_listArr removeAllObjects];
                [self downloadData:_url];
            }
        } andFalse:^(NSError *error) {
            [self.view removeAnyView];
        }];
    }
}

- (void)Btn1Click:(UIButton *)btn
{
    //退款
    [THWManager PostHttp:API(MineOrderRefund) Parameters:@{@"orderId":_listArr[btn.tag][@"orderId"], @"userToken":[Utils getUserToken]} Success:^(id responseObject) {
        if ([TXUtilsString isBlankString:responseObject[@"data"][@"refunds"]]) {
            MineRefundViewController *refund = [[MineRefundViewController alloc] init];
            refund.reasonDic = responseObject[@"data"][@"datas"];
            refund.moneyStr = responseObject[@"data"][@"totalMoney"];
            refund.orderId = responseObject[@"data"][@"orderId"];
            [self.navigationController pushViewController:refund animated:YES];
        }else{
            
        }
    } andFalse:^(NSError *error) {

    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 48;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 40;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MineOrderDetailViewController *detail = [[MineOrderDetailViewController alloc] init];
    detail.orderId = [_listArr[indexPath.section][@"list"][indexPath.row] objectForKey:@"orderId"];
    detail.type = _type;
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
